import URI from 'urijs';
import settings from '@/settings'

export const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

export const isAdmin = (user) => {
    return user.userType === -1 && user.orgId === -1
}

export const setType = async (file) => {
        const name = file.name;
        const n = name.lastIndexOf("."),
            ext = name.substr(n + 1, name.length - 1).toLowerCase();
        if (["png", "jpeg", "jpg", "gif", "bmp"].indexOf(ext) >= 0) {
            // file.src = await getBase64(file.originFileObj);
            file.src = await getBase64(file);
        } else {
            const type = ["doc", "docx"].indexOf(ext) >= 0 ? "doc" : ["ppt", "pptx"].indexOf(ext) >= 0 ? "ppt" : ["xls", "xlsx"].indexOf(ext) >= 0 ? "xls" : "pdf" === ext ? "pdf" : "txt" === ext ? "txt" : "apk" === ext ? "apk" : "bak" === ext ? "bak" : "cs" === ext ? "cs" : "csv" === ext ? "csv" : "exe" === ext ? "exe" : "fla" === ext ? "fla" : "html" === ext ? "html" : "ipa" === ext ? "ipa" : "java" === ext ? "java" : "js" === ext ? "js" : "mp3" === ext ? "mp3" : "mp4" === ext ? "mp4" : "php" === ext ? "php" : "rar" === ext ? "rar" : "swf" === ext ? "swf" : "ttf" === ext ? "ttf" : "vss" === ext ? "vss" : "xsd" === ext ? "xsd" : "zip" === ext ? "zip" : "youdaonote" === ext ? "youdaonote" : "evernote" === ext ? "evernote" : "yinxiang" === ext ? "yinxiang" : "quip" === ext ? "quip" : "onenote" === ext ? "onenote" : "onedrive" === ext ? "onedrive" : "box" === ext ? "box" : "shimo" === ext ? "shimo" : "processon" === ext ? "processon" : "default";
            file.src = require(`../assets/images/type/${type}.png`)
        }
    };

// const idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'];
// const numbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
// export const numberFormat = (value) => {
//     value = value + '';
//     const len = value.length - 1;
//     return value.replace(/([1-9]|0+)/g, function($, $1, idx, full) {
//         let pos = 0;
//         if ($1[0] !== '0') {
//             pos = len - idx;
//             if (idx === 0 && $1[0] === 1 && idxs[len - idx] === '十') {
//                 return idxs[len - idx];
//             }
//             return numbers[$1[0]] + idxs[len - idx];
//         } else {
//             const left = len - idx;
//             const right = len - idx + $1.length;
//             if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
//                 pos = left - left % 4;
//             }
//             if (pos) {
//                 return idxs[pos] + numbers[$1[0]];
//             } else if (idx + $1.length >= len) {
//                 return '';
//             } else {
//                 return numbers[$1[0]]
//             }
//         }
//     });
// }

// export const download = (blob, fileName) => {
//     if (window.navigator.msSaveOrOpenBlob) {
//         navigator.msSaveBlob(blob, fileName);
//     } else {
//         var link = document.createElement('a');
//         var href = window.URL.createObjectURL(blob);
//         link.href = href;
//         link.download = fileName;
//         document.body.appendChild(link);
//         var evt = document.createEvent("MouseEvents");
//         evt.initEvent("click", false, false);
//         link.dispatchEvent(evt);
//         document.body.removeChild(link);
//         window.URL.revokeObjectURL(href);
//     }
// }

const uid = '__download'

export const download = (url, params) => {
    var iframe = document.getElementById(uid);
    if (!iframe) {
        iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.setAttribute('id', uid);
        document.body.appendChild(iframe);
    }

    var uri = new URI(url);
    url = uri.search({
        ...uri.search(true),
        ...params,
        temp: new Date().getTime()
    }).normalize().toString();

    iframe.src = `${settings.base}/${url}`;
}

export const toBytes = bytes => {
    bytes = parseInt(bytes, 10);
    if (isNaN(bytes)) return '';
    if (bytes === 0) return '0 B';

    const k = 1024;

    const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    if (i > sizes.length - 1) {
        return 'max';
    }

    return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
}

export const mapping = (value, object) => {
    if (value == null) return value;
	if (Array.isArray(object)) {
		var _item = object.filter(function(item) {
			var val = item.id == null ? item.value : item.id;
			return val != null && val.toString() === value.toString();
		})[0];
		return _item ? _item.name || _item.value : value;
	} else {
		return object[value] || value;
	}
}